package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
)

//实体列表
type DbUserEntityListData struct {
    EntityName string `db:"Fname" json:"name"`
}

type DisplayEntityListByUserCgi struct {
	Common.CgiBase
	DbEntity []DbUserEntityListData
}

func (cgi *DisplayEntityListByUserCgi)quertEntityList() (bool) {
	sql := "select Fname from db_entity_suggest where Fuser=?;"
	err := Databases.Db.Select(&cgi.DbEntity, sql, cgi.Input["user"])
	if err != nil {
		fmt.Println("exec failed, ", err)
		return false
	}
    return true
}

func (cgi *DisplayEntityListByUserCgi)transformEntity() (string){
    str, _ := json.Marshal(cgi.DbEntity)
    str_res := string(str)
    return str_res
}

func (cgi *DisplayEntityListByUserCgi)processParam(c *gin.Context) {
	cgi.Input["user"] = c.Query("user")
}

func DisplayEntityListByUser(c *gin.Context) {
	var cgi DisplayEntityListByUserCgi
	cgi.Init(c)
	cgi.processParam(c)

	res := cgi.quertEntityList()
	if (!res) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "query fail",
	        "data": "{}",
	    })
	    return
	}

	json_res := cgi.transformEntity()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

